//
//  LoginViewController.m
//  大秀
//
//  Created by admin on 16/4/22.
//  Copyright © 2016年 yunzhen. All rights reserved.
//

#import "LoginViewController.h"
#import "HomeController.h"
#import "HomeViewController.h"
#import "MainTabBarController.h"
#import "FogetSecreateViewController.h"
#import "PersonCenterController.h"
#import "LoginModel.h"
#import "ZYUtils.h"
@interface LoginViewController ()<UITextFieldDelegate>
@property (nonatomic ,weak)UITextField *InputNub;
@property (nonatomic ,weak)UITextField *InputSecreatNub;
@property (nonatomic ,strong)LoginModel *loginModel;
@end

@implementation LoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:240/255.0 green:239/255.0 blue:237/255.0 alpha:1];
    [self makeUI];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}


- (void)makeUI{

    
    self.navigationItem.titleView.tintColor = [UIColor whiteColor];
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 50, 50)];
    title.font = [UIFont systemFontOfSize:18.0];
    title.textAlignment = NSTextAlignmentCenter;
    title.text = @"登录";
    title.textColor = [UIColor grayColor];
    self.navigationItem.titleView = title;

    UITextField *InputNub = [[UITextField alloc]initWithFrame:CGRectMake(0, 74, kScreenWidth, 45)];
    InputNub.textAlignment = NSTextAlignmentLeft;
    InputNub.textColor = [UIColor grayColor];
    InputNub.placeholder = @"  输入账号";
    InputNub.backgroundColor = [UIColor whiteColor];
    InputNub.delegate = self;
    InputNub.clearButtonMode = UITextFieldViewModeAlways;
    self.InputNub = InputNub;
    [self.view addSubview:InputNub];
    
    
    UITextField *InputSecreatNub = [[UITextField alloc]initWithFrame:CGRectMake(0, 130, kScreenWidth, 45)];
    InputSecreatNub.textAlignment = NSTextAlignmentLeft;
    InputSecreatNub.textColor = [UIColor grayColor];
    InputSecreatNub.placeholder = @"  输入密码";
    InputSecreatNub.delegate = self;
    InputSecreatNub.clearButtonMode = UITextFieldViewModeAlways;
    InputSecreatNub.secureTextEntry = YES;
    self.InputSecreatNub = InputSecreatNub;
    InputSecreatNub.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:InputSecreatNub];
    
    
    UIButton *fogetSecreateBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth - 100, 180, 100, 45)];
    [fogetSecreateBtn setTitle:@"忘记密码" forState:UIControlStateNormal];
    fogetSecreateBtn.titleLabel.font = [UIFont systemFontOfSize:13.0];
    [fogetSecreateBtn addTarget:self action:@selector(forgetSecreate) forControlEvents:UIControlEventTouchUpInside];
    [fogetSecreateBtn setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
    [self.view addSubview:fogetSecreateBtn];
    

    UIButton *LoginBtn = [[UIButton alloc]initWithFrame:CGRectMake(20, 230, kScreenWidth - 40, 45)];
    LoginBtn.backgroundColor = [UIColor colorWithRed:92/255.0 green:167/255.0 blue:252/255.0 alpha:1];
    [LoginBtn setTitle:@"登陆" forState:UIControlStateNormal];
    [LoginBtn addTarget:self action:@selector(Login) forControlEvents:UIControlEventTouchUpInside];
    LoginBtn.layer.cornerRadius = 5.0f;
    [LoginBtn.layer setMasksToBounds:YES];
    [self.view addSubview:LoginBtn];
}
- (void)forgetSecreate{
    
    [self.navigationController pushViewController:[FogetSecreateViewController new] animated:YES];

}
- (void)Login{
    
    if (self.InputNub.text.length == 0) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"请输入账号";
        [hud hide:YES afterDelay:1];
        
    }else if(!([ZYUtils validateEmail:self.InputNub.text]||[ZYUtils validateMobile:self.InputNub.text])){
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"账号为手机号或邮箱";
        [hud hide:YES afterDelay:1];

    }else if (self.InputSecreatNub.text.length == 0) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"请输入密码";
        [hud hide:YES afterDelay:1];
    }else if (self.InputSecreatNub.text.length>18||self.InputSecreatNub.text.length<6) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.mode = MBProgressHUDModeText;
        hud.labelText = @"密码长度在6-8位之间";
        [hud hide:YES afterDelay:1];
        
    }else if(self.InputSecreatNub.text.length>=6&&self.InputSecreatNub.text.length<=18){
        
        Reachability *reach = [Reachability reachabilityForInternetConnection];
        NetworkStatus status = [reach currentReachabilityStatus];
        if (status == NotReachable) {
            
            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
            HUD.labelText = @"请检查网络连接";
            HUD.mode = MBProgressHUDModeText;
            [HUD hide:YES afterDelay:1.0];
            
            return;
            
        }

        NSDictionary *params = @{@"username":self.InputNub.text};
        [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/if_user_existed?" params:params success:^(id json) {
           NSString *str = json[@"count"];
            int a = [str intValue];
            NSLog(@"%@",str);
            
            if (a == 1) {
                
                MBProgressHUD *HUD1 = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD1.labelText = @"正在登陆...";
                HUD1.mode = MBProgressHUDModeIndeterminate;
                
                NSDictionary *params = @{@"username":self.InputNub.text,@"password":self.InputSecreatNub.text};
                
                [HttpTool postWithURL:@"http://61.135.176.43:6080/bigtobig/user/login?" params:params success:^(id json) {
                    
                    NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
                    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                    NSLog(@"%@",dict);
                    

                    if (dict.count != 0) {
                        
                        [UIView animateWithDuration:1.0 animations:^{
                            
                            HUD1.hidden = YES;
                            
                            [NSThread sleepForTimeInterval:1];
                            
                            MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                            HUD.labelText = @"登陆成功";
                            HUD.mode = MBProgressHUDModeText;
                            [HUD hide:YES afterDelay:1.0];
                            
                        } completion:^(BOOL finished) {
                            
//                            [self sdkLogin];
                            
                            //登录成功后保存下这个值判断程序启动的时候登陆过直接进入否则进入登录界面
                            NSUserDefaults* isLogin = [NSUserDefaults standardUserDefaults];
                            [isLogin setBool:YES forKey:@"isOn"];
                            [isLogin synchronize];
                            

                            NSUserDefaults* inputSecreate = [NSUserDefaults standardUserDefaults];
                            [inputSecreate setObject:self.InputSecreatNub.text forKey:@"Secreate"];
                            [inputSecreate synchronize];
                            
                            NSUserDefaults* inputNub = [NSUserDefaults standardUserDefaults];
                            [inputNub setObject:self.InputNub.text forKey:@"InputNub"];
                            [inputNub synchronize];
                            

                            KeyWindow.rootViewController = [MainTabBarController new];
                            
                        }];
                        
                        
                    }else{
                        
                        HUD1.hidden = YES;
                        [NSThread sleepForTimeInterval:0.5];

                        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                        HUD.labelText = @"密码错误";
                        HUD.mode = MBProgressHUDModeText;
                        [HUD hide:YES afterDelay:1.0];
                    }
                    
                } failure:^(NSError *error) {
                    

                    
                }];
                
            }else{
            
                
                MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
                HUD.labelText = @"账号未注册";
                HUD.mode = MBProgressHUDModeText;
                [HUD hide:YES afterDelay:1.0];
            }
        } failure:^(NSError *error) {
            
            
        }];

        
    }

}

//- (void)sdkLogin{
//
//    [AVCamViewController getLoginUserInfo:self.loginModel.primary_key withPassword:self.InputSecreatNub.text withBlock:^(NSString *code, NSInteger activityId, NSInteger userId, NSString *tokenId) {
//        
//        //登陆成功
//        if ([code isEqualToString:@"0"])
//        {
//            
//            
//            NSLog(@"%d",activityId);
//      
//            NSString *str = [NSString stringWithFormat:@"%d",activityId];
//            NSUserDefaults *activityIdDefaults = [NSUserDefaults standardUserDefaults];
//            [activityIdDefaults setObject:str forKey:@"activty_id"];
//            [activityIdDefaults synchronize];
//            
//
//            dispatch_async(dispatch_get_main_queue(), ^{
//
//
//            });
//            
//        }else
//        {
//            NSLog(@"登陆失败");
//        }
//    }];
//
//}
///调用方法  设置只能输入数字  和   限制字符长度
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
    

    if (self.InputSecreatNub == textField) {
    
        
        NSUInteger proposedNewLength = textField.text.length - range.length + string.length;
        
        if (proposedNewLength > 18)
            
            return NO;//限制长度
        
    }
    
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.InputNub endEditing:YES];
    [self.InputSecreatNub endEditing:YES];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField{

    return [self.InputSecreatNub endEditing:YES];
}
@end
